/*****************************************************************************
 *  CommLayerLib for Android - TCPClient.java
 *  Copyright (C) 2012  Matteo Piscitelli
 *  E-mail: matteo@picciux.it
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  For further info, check http://code.google.com/p/java-comm-layer/
 *
 *  SVN: $Id: TCPClient.java 34 2012-10-09 18:21:04Z picciux@gmail.com $
 *  
 *****************************************************************************/

package it.picciux.commlayer.android.net;

import it.picciux.commlayer.CommLayerException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPClient extends it.picciux.commlayer.net.TCPClient {
	protected Socket sock;

	public TCPClient() {
		super();
		sock = null;
	}

	public TCPClient(Socket clientSocket) {
		super();
		sock = clientSocket;
	}

	@Override
	protected void retrieveRemoteAddress() {
		address = sock.getInetAddress().getHostAddress();
		port = sock.getPort();
	}

	@Override
	public void disconnect() {
		try {
			sock.close();
		} catch (IOException e) { /* do nothing */ }
		connected = false;
	}

	@Override
	protected boolean tryConnection() throws CommLayerException {
		try {
			sock = new Socket(address, port);
		} catch (UnknownHostException e) {
			throw new CommLayerException(e.getMessage(), NetworkLayer.UNKNOWN_HOST);
		} catch (IOException e) {
			throw new CommLayerException(e.getMessage(), NetworkLayer.CONNECTION_ERROR);
		}
		return true;
	}


	@Override
	protected void destroy() {
		try { sock.close(); } catch (IOException e) {}
	}

	@Override
	public InputStream getInputStream() throws IOException {
		if (sock != null)
			return sock.getInputStream();
		else
			return null;
	}

	@Override
	public OutputStream getOutputStream() throws IOException {
		if (sock != null)
			return sock.getOutputStream();
		else
			return null;
	}

}
